// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Collections.Generic;

namespace SnapObjects.Data
{
    public static class DynamicModelExtensions
    {
        public static string ToXmlString(this DynamicModel model)
        {
            var writer = new XNodeWriter();

            WriteXml(model, writer);

            return writer.ToString();
        }

        public static string ToXmlString(this IEnumerable<DynamicModel> models)
        {
            var writer = new XNodeWriter();

            writer.WriteAsArray("DynamicModels");

            foreach (var model in models)
            {
                WriteXml(model, writer);
            }

            writer.WriteEndArray();

            return writer.ToString();
        }

        private static void WriteXml(DynamicModel model, XNodeWriter writer)
        {
            writer.WriteAsObject("DynamicModel");

            foreach (var p in model.Properties)
            {
                writer.WriteAsValue(p.Name).WriteValue(model.GetValue(p.Index));
            }

            writer.WriteEndObject();
        }

        public static string ToJsonString(this DynamicModel model)
        {
            var provider = JsonProviderFactory.Create();

            var writer = provider.GetNodeWriter();

            WriteJson(model, writer);

            return writer.ToString();
        }

        public static string ToJsonString(this IEnumerable<DynamicModel> models)
        {
            var provider = JsonProviderFactory.Create();

            var writer = provider.GetNodeWriter();

            writer.WriteAsArray("");

            foreach (var model in models)
            {
                WriteJson(model, writer);
            }

            writer.WriteEndArray();

            return writer.ToString();
        }

        private static void WriteJson(DynamicModel model, INodeWriter writer)
        {
            writer.WriteAsObject("");

            foreach (var p in model.Properties)
            {
                writer.WriteAsValue(p.Name)
                    .WriteValue(model.GetValue(p.Index));
            }

            writer.WriteEndObject();
        }
    }
}
